import router from './router'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'
import { asyncRoutes } from '@/router/index'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 拿到信息:名字，头像，menus:[可以访问的页面]
      if (!store.getters.userId) {
        const res = await store.dispatch('user/getProfile')
        console.log('接收的信息', res)
        // (1) 8个页面能访问几个?asyncRoutes .filter
        // (2) 如何判断 第一个页面能被访问?这个路由的name是不是在后端返回的数组中出现?
        // return 后端返回的数组.includes(路由的name)
        // 筛选出对应的
        const filterRoutes = asyncRoutes.filter(item => {
          return res.roles.menus.includes(item.children[0].name)
        })
        // 动态生成当前的用户能访问的页面
        //  asyncRoutes 一共有8个页面  从asyncRoutes中选出当前用户能访问的页面

        console.log('筛选后返回的数组', filterRoutes)

        // 补充494，在最末尾
        // 404 page must be placed at the end !!!
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        // 1. 渲染左侧菜单  filteredRoutes ====> vuex
        store.commit('menus/getMenus', filterRoutes)
        // 2。添加到路由配置
        router.addRoutes(filterRoutes)

        // vuerouter addRoutes 白屏
        next(to)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  next()
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

